package pers.zxk.jlytnews.servlet;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import pers.zxk.jlytnews.base.BaseServlet;
import pers.zxk.jlytnews.dao.FoodMenuDao;
import pers.zxk.jlytnews.dao.impl.FoodMenuDaoImpl;
import pers.zxk.jlytnews.entity.FoodMenu;
import pers.zxk.jlytnews.entity.FoodMenuWithFood;
import pers.zxk.jlytnews.manager.UserStateManager;
import pers.zxk.jlytnews.util.CommonUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.List;


@MultipartConfig
public class FoodMenuServlet extends HttpServlet {
    private FoodMenuDao mFoodMenuDao = new FoodMenuDaoImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取能够与“url-pattern”中匹配的路径
        String method = req.getServletPath();

        //(此时处理的请求是查询 query.do)
        System.out.println("request.getServletPath()获取的值为: " + method);//输出 /query.do

        //2.通过字符串截取，把方法名 query 截取出来
        int i = method.lastIndexOf("/");
        method = method.substring(i + 1, method.length());

        System.out.println("截取后的值为： " + method);

        Method m = null;
        try {
            //3.获取当前类中名字为 method 的方法
            m = this.getClass().getDeclaredMethod(method,
                    HttpServletRequest.class, HttpServletResponse.class);

            //4.调用 method 方法
            m.setAccessible(true);
            m.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addFoodMenu(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        //判断用户权限
        if(!UserStateManager.isAdmin(req)){
            CommonUtil.sendJsonData(resp, null, 1, "无权操作！");
            return;
        }

        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String foodId = req.getParameter("foodId");
        String date = req.getParameter("date");
        String time = req.getParameter("time");
        String description = req.getParameter("description");
        String remarks = req.getParameter("remarks");

        //更新数据并向客户端返回消息
        try {
            if (mFoodMenuDao.addFoodMenu(Integer.parseInt(foodId), date, time, description, remarks)) {
                CommonUtil.sendJsonData(resp, "添加成功", 0, "");
            } else {
                CommonUtil.sendJsonData(resp, "添加失败", 1, "");
            }
        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, "添加失败", 1, exception.getMessage());
        }
    }

    public void addFoodMenus(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        //判断用户权限
        if(!UserStateManager.isAdmin(req)){
            CommonUtil.sendJsonData(resp, null, 1, "无权操作！");
            return;
        }

        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String jsonData = req.getParameter("data");//获取参数的数据
        JSONObject jsonObject= JSONObject.fromObject(jsonData);//将数据转换成jsonobject
        Object data = jsonObject.get("foodmenus");//提取jsonobject中的key为foodmenus的数据
        JSONArray jsonArray = JSONArray.fromObject(data);//将数据转换成jsonarray
        boolean isSuccess = false;
        try {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject object = jsonArray.getJSONObject(i);
                int foodId = object.getInt("foodId");
                String date = object.getString("date");
                String time = object.getString("time");
                String description = object.getString("description");
                String remarks = object.getString("remarks");

                isSuccess = mFoodMenuDao.addFoodMenu(foodId, date, time, description, remarks);
            }
            if (isSuccess) {
                CommonUtil.sendJsonData(resp, "添加成功", 0, "");
            } else {
                CommonUtil.sendJsonData(resp, "添加失败", 1, "");
            }
        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, "添加失败", 1, exception.getMessage());
        }
    }

    public void delFoodMenu(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //判断用户权限
        if(!UserStateManager.isAdmin(req)){
            CommonUtil.sendJsonData(resp, null, 1, "无权操作！");
            return;
        }

        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String id = req.getParameter("id");

        //更新数据并向客户端返回消息
        try {
            if (mFoodMenuDao.delFoodMenu(Integer.parseInt(id))) {
                CommonUtil.sendJsonData(resp, "删除成功", 0, "");
            } else {
                CommonUtil.sendJsonData(resp, "删除失败", 1, "");
            }
        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, "删除失败", 1, exception.getMessage());
        }
    }

    public void updateFoodMenu(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        //判断用户权限
        if(!UserStateManager.isAdmin(req)){
            CommonUtil.sendJsonData(resp, null, 1, "无权操作！");
            return;
        }

        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String id = req.getParameter("id");
        String foodId = req.getParameter("foodId");
        String date = req.getParameter("date");
        String time = req.getParameter("time");
        String description = req.getParameter("description");
        String remarks = req.getParameter("remarks");

        //更新数据并向客户端返回消息
        try {
            if (mFoodMenuDao.updateFoodMenu(Integer.parseInt(id), Integer.parseInt(foodId), date, time, description, remarks)) {
                CommonUtil.sendJsonData(resp, "更新成功", 0, "");
            } else {
                CommonUtil.sendJsonData(resp, "更新失败", 1, "");
            }
        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, "更新失败", 1, exception.getMessage());
        }
    }

    public void getFoodMenu(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 对请求包设置编码
        req.setCharacterEncoding("utf-8");

        //获取Request传递（POST）过来的数据
        String date = req.getParameter("date");
        String time = req.getParameter("time");

        //查询数据
        try {
            List<FoodMenuWithFood> list = null;
            if (time.equals("")) {
                list = mFoodMenuDao.getFoodMenu(date);
            } else {
                list = mFoodMenuDao.getFoodMenu(date, time);
            }
            JSONArray jsonArray = JSONArray.fromObject(list);
            if (jsonArray != null) {
                CommonUtil.sendJsonData(resp, jsonArray, 0, "");
            } else {
                CommonUtil.sendJsonData(resp, null, 1, "信息获取失败");
            }
        } catch (Exception exception) {
            CommonUtil.sendJsonData(resp, null, 1, exception.getMessage());
        }
    }

}
